using System;
using System.Threading.Tasks;
using HengTong.Model.Db.SupplyChain.Material;
using WalkingTec.Mvvm.Core;
using UUIDNext;
using HengTong.Model.Db.SupplyChain.Purchase;
using Microsoft.EntityFrameworkCore;


namespace HengTong.ViewModel.SupplyChain.SysPurchaseRequestBillEntryVms
{
    public partial class SysPurchaseRequestBillEntryVm : CrudVm<SysPurchaseRequestBillEntry>
    {

        public SysPurchaseRequestBillEntryVm()
        {
            SetInclude(x => x.Bill);
            SetInclude(x => x.Material);
            SetInclude(x => x.MaterialSku);
        }

        protected override void InitVM()
        {
        }

        public override async Task DoAddAsync()
        {
            if (Entity is IBasePoco poco)
            {
                poco.CreateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.CreateTime = DateTime.Now;
                poco.UpdateTime = DateTime.Now;
            }
            var sku = await DC.Set<SysMaterialSku>()
                .AsNoTracking()
                .FirstOrDefaultAsync(e => e.ID == Entity.MaterialSkuId);
            if (sku == null)
            {
                MSD.AddModelError(nameof(Entity.MaterialSkuId), "物料规格不存在，无法新增采购申请单明细");
                return;
            }
            Entity.MaterialId = sku.MaterialId;
            Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
            await base.DoAddAsync();
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            if (Entity is IBasePoco poco)
            {
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateTime = DateTime.Now;
            }
            var sku = await DC.Set<SysMaterialSku>()
                .AsNoTracking()
                .FirstOrDefaultAsync(e => e.ID == Entity.MaterialSkuId);
            if (sku == null)
            {
                MSD.AddModelError(nameof(Entity.MaterialSkuId), "物料规格不存在，无法编辑采购申请单明细");
                return;
            }
            Entity.MaterialId = sku.MaterialId;
            await base.DoEditAsync(updateAllFields);
        }

    }
}
